<?php

namespace App\Http\Middleware;

use App\Models\System\User;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Route;
use Closure;

/**
 * 后台日志中间件
 * @package App\Http\Middleware
 */
class AdminOperateLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //是否记录日志
        $isRecord = false;
        //当前焦点菜单，控制左侧选中菜单路由名称
        $curRoute = $request->route();
        $curRouteName = $curRoute[1]['as'] ?? '';
        //权限service类
        $permSer = new \App\Services\System\Permission();
        //当前权限数据
        $curPermData = $permSer->getCacheSimplePermDataByName($curRouteName);
        //请求方式为POST/PUT强制记录日志
        $method = $request->getMethod();
        if (in_array($method, ['POST', 'PUT'])){
            $isRecord = true;
        }else{
            if (isset($curPermData['is_opertion_log']) && $curPermData['is_opertion_log']){
                $isRecord = true;
            }
        }
        //dd($curRouteName, $curPermData);
        //$isRecord = true;
        //权限如果标记记录日志，则存储日志
        if ($isRecord){
            //面包屑数据
            $breadcrumbList = $permSer->getBreadcrumbData(isset($curPermData['perm_id']) ? $curPermData['perm_id'] : 0);
            $collection = collect($breadcrumbList);
            $actList = $collection->pluck('display_name');
            //日志数据
            $logData = [
                'user_id' => $request->user()->id ?? 0,
                'user_name' => $request->user()->name ?? '',
                'opertion_name' => $actList->implode('->'),
                'perm_id' => $curPermData['perm_id'] ?? 0,
                'route_name' => $curRouteName,
                'ip' => $request->getClientIp(),//getCustomerIp()
                'request_data' => $request->input(),
                'add_time' => time(),
            ];
            //由于登录时未带header投无法解析当前登录用户，故此处手动补充当前用户
            if ($curRouteName == 'admin.login.account'){
                $email = $request->input('email');
                $user = User::query()->where('email', $email)->first();
                $user && $logData['user_id'] = $user->id;
                $user && $logData['user_name'] = $user->name;
            }
            //调用队列写入日志
            dispatch(new \App\Jobs\SysOperateLogSave($logData))->onQueue('low');
        }

        return $next($request);
    }
}
